from flask import Flask, render_template, request, redirect, url_for
import sqlite3
from nltk.sentiment.vader import SentimentIntensityAnalyzer
import datetime

app = Flask(__name__)
app.config['DATABASE'] = 'sentiment_analysis.db'

# 初始化情感分析器
try:
    sia = SentimentIntensityAnalyzer()
except LookupError:
    # 如果缺少资源，提示用户下载
    import nltk
    print("请先下载NLTK的vader_lexicon资源：")
    print("import nltk")
    print("nltk.download('vader_lexicon')")
    exit()

# 连接数据库
def get_db():
    conn = sqlite3.connect(app.config['DATABASE'])
    conn.row_factory = sqlite3.Row
    return conn

# 初始化数据库
def init_db():
    with app.app_context():
        db = get_db()
        db.execute('''
            CREATE TABLE IF NOT EXISTS analysis_history (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                text TEXT NOT NULL,
                sentiment TEXT NOT NULL,
                score REAL NOT NULL,
                timestamp TEXT NOT NULL
            )
        ''')
        db.commit()

# 分析文本情感
def analyze_sentiment(text):
    # 使用VADER情感分析器获取情感分数
    scores = sia.polarity_scores(text)
    compound_score = scores['compound']
    
    # 根据复合分数判断情感倾向
    if compound_score >= 0.05:
        sentiment = '正面'
    elif compound_score <= -0.05:
        sentiment = '负面'
    else:
        sentiment = '中性'
    
    return sentiment, compound_score

@app.route('/')
def index():
    # 显示历史记录
    db = get_db()
    history = db.execute('SELECT * FROM analysis_history ORDER BY timestamp DESC LIMIT 10').fetchall()
    db.close()
    return render_template('index.html', history=history)

@app.route('/analyze', methods=['POST'])
def analyze():
    text = request.form['text']
    if not text.strip():
        return redirect(url_for('index'))
    
    # 分析情感
    sentiment, score = analyze_sentiment(text)
    
    # 保存到历史记录
    timestamp = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    db = get_db()
    db.execute(
        'INSERT INTO analysis_history (text, sentiment, score, timestamp) VALUES (?, ?, ?, ?)',
        (text, sentiment, score, timestamp)
    )
    db.commit()
    db.close()
    
    return redirect(url_for('results', text=text, sentiment=sentiment, score=score))

@app.route('/results')
def results():
    text = request.args.get('text')
    sentiment = request.args.get('sentiment')
    score = request.args.get('score')
    return render_template('results.html', text=text, sentiment=sentiment, score=score)

@app.route('/clear_history')
def clear_history():
    db = get_db()
    db.execute('DELETE FROM analysis_history')
    db.commit()
    db.close()
    return redirect(url_for('index'))

if __name__ == '__main__':
    # 初始化数据库
    init_db()
    # 运行应用
    app.run(debug=True)